import { BookOutlined } from '@ant-design/icons'
import { useRefValue } from '@gnlab/utils/env-react'
import { Tooltip, Tag, message, Button } from 'antd'
import ChooseExternalTagsModal from '@/desktop/components/ChooseExternalTags'
import ChooseGroupTagsModal from '@/desktop/components/ChooseGroupTags'
import services from '@/services'
import type { ExternalItemTag, GroupTag } from '@/services/contact-types'
import './choose-tags.module.less'

export function ChooseExternalTags(props: {
  choosed: ExternalItemTag[] | null
  onChoosed: (choosed: ExternalItemTag[] | null) => void
}) {
  const { choosed: currentChoosed, onChoosed } = props

  const [choosing, setChoosing] = useState(false)
  const onFinish = useCallback(
    (choosed?: ExternalItemTag[]) => {
      if (choosed) onChoosed(choosed.length ? choosed : null)
      else onChoosed(currentChoosed)
      setChoosing(false)
    },
    [currentChoosed, onChoosed],
  )

  return <>
    <Tooltip title="按标签检索" placement="top">
      <BookOutlined styleName="choose-tags" onClick={() => setChoosing(true)} />
    </Tooltip>

    <ChooseExternalTagsModal
      visible={choosing}
      title="按标签搜索客户（在线企微数量多时耗时会较长）"
      choosed={currentChoosed?.map(t => t.id)}
      onFinish={onFinish}
    />
  </>
}

export function ChoosedExternalTags(props: {
  visible: boolean
  choosed: ExternalItemTag[] | null
  onUpdated: (choosed: ExternalItemTag[] | null) => void
  onRefresh: () => void
}) {
  const { visible, choosed, onUpdated, onRefresh } = props

  const onRemove = useCallback(
    (e: React.MouseEvent<HTMLElement>, id: string) => {
      e.preventDefault()
      const _choosed = choosed!.filter(t => t.id !== id)
      onUpdated(_choosed.length ? _choosed : null)
    },
    [choosed, onUpdated],
  )

  const leavedRef = useRef(false)
  useEffect(() => {
    leavedRef.current = false
    return () => {
      leavedRef.current = true
    }
  }, [])

  const [syncing, setSyncing] = useState(false)
  const choosedRef = useRefValue(choosed)
  const sync = useCallback(async () => {
    const tagIds = choosedRef.current?.map(v => v.id)
    if (!tagIds || !tagIds.length) return

    setSyncing(true)
    const res = await services.externals.tags.syncAllContactTags(tagIds)
    setSyncing(false)
    if (res.success) {
      if (!leavedRef.current) onRefresh() // 若已离开界面，不触发刷新
    } else {
      void message.error(res.error.replace(' 秒', '秒'))
    }
  }, [onRefresh])

  if (!visible || !choosed || !choosed.length) return null

  return <section styleName="choosed-tags">
    {choosed.map(tag => <Tag key={tag.id} closable onClose={e => onRemove(e, tag.id)}>
      {tag.name}
    </Tag>)}

    {/*<div styleName="sync">*/}
    {/*  找不到客户？*/}
    {/*  <Button type="link" onClick={sync} css={{ padding: '0', fontSize: '12px' }} loading={syncing}>*/}
    {/*    点此同步客户信息*/}
    {/*  </Button>*/}
    {/*</div>*/}
  </section>
}

export function ChooseGroupTags(props: {
  choosed: GroupTag[] | null
  onChoosed: (choosed: GroupTag[] | null) => void
}) {
  const { choosed: currentChoosed, onChoosed } = props

  const [choosing, setChoosing] = useState(false)
  const onFinish = useCallback(
    (choosed?: GroupTag[]) => {
      if (choosed) onChoosed(choosed.length ? choosed : null)
      else onChoosed(currentChoosed)
      setChoosing(false)
    },
    [currentChoosed, onChoosed],
  )

  return <>
    <Tooltip title="按标签检索" placement="top">
      <BookOutlined styleName="choose-tags" onClick={() => setChoosing(true)} />
    </Tooltip>
    <ChooseGroupTagsModal
      visible={choosing}
      title="按标签搜索群"
      choosed={currentChoosed?.map(t => t.id)}
      onFinish={onFinish}
    />
  </>
}

export function ChoosedGroupTags(props: {
  visible: boolean
  choosed: GroupTag[] | null
  onUpdated: (choosed: GroupTag[] | null) => void
}) {
  const { visible, choosed, onUpdated } = props

  const onRemove = useCallback(
    (e: React.MouseEvent<HTMLElement>, id: number) => {
      e.preventDefault()
      const _choosed = choosed!.filter(t => t.id !== id)
      onUpdated(_choosed.length ? _choosed : null)
    },
    [choosed, onUpdated],
  )

  if (!visible || !choosed || !choosed.length) return null

  return <section styleName="choosed-tags group-tag">
    {choosed.map(tag => <Tag key={tag.id} closable onClose={e => onRemove(e, tag.id)}>
      {tag.name}
    </Tag>)}
  </section>
}
